package com.zhongxi.guoyuan.fragment.RewardCoinOrder;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.rewardCoinOrder.RewardOrderHasNoApplyAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.ItemGoodAttr;
import com.zhongxi.guoyuan.entity.coinStore.NoPayAddress;
import com.zhongxi.guoyuan.entity.coinStore.PostcartAttrsCollection;
import com.zhongxi.guoyuan.entity.coinStore.SelcetPostCartGoodsAttrs;
import com.zhongxi.guoyuan.entity.coinStore.ShopInfos;
import com.zhongxi.guoyuan.entity.rewardcoin.MirrorInfo;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderInfo;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.view.rewardCoin.ApplyRewardActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static android.R.attr.data;

/**
 * A simple {@link Fragment} subclass.
 */
public class RewardOrderHasNoApplyFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView lvList;
    private List<RewardCoinOrderInfo> mydata = new ArrayList<>();
    private RewardOrderHasNoApplyAdapter adapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pos = msg.getData().getInt("pos");
            switch (msg.what) {
                case 0:
                    toPay(msg.getData().getString("orderId"), Integer.parseInt(msg.getData().getString("post")), msg.getData().getString("shopId"));
                    break;
                case 1:
                    deleteNopay();
                    break;
            }
        }
    };
    private String type;
    private JSONObject orderCus;

    private void deleteNopay() {
        type = "delete";
        Map<String, String> map = new HashMap<>();
        map.put("ordertype", mydata.get(pos).getOrdertype());
        map.put("orderid", mydata.get(pos).getId());

        getServer(Url.REWARD_DETAIL_NOPAY_LIST, map, "", false, null, "post");
    }

    private JSONObject info;
    private JSONObject shopInfo;
    private ListView listView;
    private int pos;

    /**
     * 去支付
     *
     * @param orderId
     * @param post
     * @param shopId
     */
    private void toPay(String orderId, int post, String shopId) {
        try {
            ArrayList<PostcartAttrsCollection> goodsList = new ArrayList<>();
            PostcartAttrsCollection postcartAttrsCollection = new PostcartAttrsCollection();
            RewardCoinOrderInfo rewardCoinOrderInfo = mydata.get(pos);
            postcartAttrsCollection.setPostage(rewardCoinOrderInfo.getPostage());
            postcartAttrsCollection.setTotalPrice(rewardCoinOrderInfo.getShouldprice());
            postcartAttrsCollection.setStoreNum(rewardCoinOrderInfo.getGoodsnum());
            postcartAttrsCollection.setTotalMD(DataUtil.formatData(rewardCoinOrderInfo.getBackinnernum()));
            postcartAttrsCollection.setTotalHD(DataUtil.formatData(rewardCoinOrderInfo.getBackredbean()));
            postcartAttrsCollection.setCustomNotes(rewardCoinOrderInfo.getRemark());
            ShopInfos shopInfos = new ShopInfos();
            JSONObject shopInfoObject = shopInfo.optJSONObject(shopId);
            shopInfos.setName(shopInfoObject.optString("name"));
            shopInfos.setId(shopInfoObject.optString("id"));
            shopInfos.setStatus(shopInfoObject.optString("status"));
            shopInfos.setAddress(shopInfoObject.optString("address"));
            shopInfos.setPhone(shopInfoObject.optString("phone"));
            shopInfos.setAmountofmail(shopInfoObject.optString("amountofmail"));
            shopInfos.setStoreNum(rewardCoinOrderInfo.getGoodsnum());
            postcartAttrsCollection.setShopInfos(shopInfos);
            JSONObject orderCusObject = orderCus.optJSONObject(orderId);
            if (null != orderCusObject && orderCusObject.length() > 0) {
                NoPayAddress address = new NoPayAddress();
                address.setId(orderCusObject.optString("shippingid"));
                address.setName(orderCusObject.optString("consignee"));
                address.setAddress(orderCusObject.optString("shippingaddress"));
                address.setPhone(orderCusObject.optString("consigneemphone"));
                postcartAttrsCollection.setAddress(address);
            }
            List<SelcetPostCartGoodsAttrs> goodsAttrses = new ArrayList<>();
            JSONArray jsonArray = info.optJSONArray(orderId);
            for (int i = 0; i < jsonArray.length(); i++) {
                SelcetPostCartGoodsAttrs goodsAttrs = new SelcetPostCartGoodsAttrs();
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                MirrorInfo mirrorInfo = MirrorInfo.parseMatch(jsonObject);
                goodsAttrs.setAttrcollection(mirrorInfo.getCollectionid());
                goodsAttrs.setBackinnernum(mirrorInfo.getBackinnernum());
                goodsAttrs.setBackredbean(mirrorInfo.getBackredbean());
                goodsAttrs.setGoodsid(mirrorInfo.getGoodsid());
                goodsAttrs.setGoodstype(mirrorInfo.getGoodstype());
                goodsAttrs.setName(mirrorInfo.getGoodsname());
                goodsAttrs.setImgUrl(mirrorInfo.getThumbnail());
                goodsAttrs.setPrice(mirrorInfo.getShouldprice());
                goodsAttrs.setBacksilvernum(mirrorInfo.getBacksilvernum());
                goodsAttrs.setGoodsnum(mirrorInfo.getGoodsnum());
                List<ItemGoodAttr> itemGoodAttrs = new ArrayList<>();
                JSONObject object = new JSONObject(mirrorInfo.getGattr());
                Iterator<String> keys = object.keys();
                while (keys.hasNext()) {
                    ItemGoodAttr itemGoodAttr = new ItemGoodAttr();
                    String next = keys.next();
                    String attrValue = object.optString(next);
                    itemGoodAttr.setAttrv(attrValue);
                    itemGoodAttrs.add(itemGoodAttr);
                }
                goodsAttrs.setItemGoodAttrs(itemGoodAttrs);
                goodsAttrses.add(goodsAttrs);
            }
            postcartAttrsCollection.setGoodsAttrses(goodsAttrses);

            goodsList.add(postcartAttrsCollection);
            Intent intentApply = new Intent(context, ApplyRewardActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("goodsList", goodsList);
            bundle.putInt("post", post);
            bundle.putString("orderId", orderId);
            intentApply.putExtras(bundle);
            startActivity(intentApply);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order_has_no_apply, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (PullToRefreshListView) getView().findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new RewardOrderHasNoApplyAdapter(context, mydata, handler, this);
        lvList.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        super.initData();
        getOrder();
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("亲,暂时还没有数据哦!");
        tv.setTextSize(20);
        //当界面为空的时候显示的视图
        lvList.setEmptyView(tv);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
            getOrder();
    }

    /**
     * 获取未支付订单
     */
    private void getOrder() {
        String str = "&page=" + pageNum;
        type = "shoplist";
        getServer(Url.REWARD_NOPAY, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("shoplist".equals(type)) {
                RewardCoinOrderResult result = gson.fromJson(response, RewardCoinOrderResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if (pageNum == 1) {
                    mydata.clear();
                }
                JSONObject obj = new JSONObject(response);
                if (result.getOrderInfo() != null && result.getOrderInfo().size() > 0) {
                    List<RewardCoinOrderInfo> orderInfo = result.getOrderInfo();
                    mydata.addAll(orderInfo);
                    info = obj.optJSONObject("orderMirror");
                    adapter.setInfo(info);

                    shopInfo = obj.optJSONObject("shopInfo");

                    adapter.setShopInfo(shopInfo);

                    orderCus = obj.optJSONObject("orderCus");

                    adapter.setOrderCus(orderCus);
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            } else if ("delete".equals(type)) {
                BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                mydata.remove(pos);
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (1000 == result.getCode()) {
                showShortToast("等待商家确认");
            } else if (2016 == result.getCode()) {
                showShortToast("订单定制信息已丢失");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(this);
        lvList.setOnRefreshListener(this);
        listView = lvList.getRefreshableView();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position - 1 == adapter.getmExpandedMenuPos()) {
            adapter.setmExpandedMenuPos(-1);
        } else {
            adapter.setmExpandedMenuPos(position - 1);
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(position);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getOrder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getOrder();
    }
}
